package com.simon.study.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * @author simon
 */
public class LengthOfLongestSubstring00003 {


    public static void main(String[] args) {
        String s = "bbbb";
        System.out.println( solution(s) );
    }




    public static int solution(String s){
        Map<Character, Integer> idxmap = new HashMap<>();

        String target = ""; int left = 0;
        for (int i = 0; i < s.length(); i++) {
            Integer idx = idxmap.get(s.charAt(i));
            if( idx != null && idx.intValue() >= left ){
                if( i - left > target.length() ){
                    target = s.substring(left, i);
                }
                left = idx+1;
            }
            idxmap.put(s.charAt(i), i);
        }
        if( (s.length() - left) > target.length() ){
            target = s.substring(left, s.length());
        }
        return target.length();
    }

    public static int solution2(String s){
        Map<Character, Integer> idxmap = new HashMap<>();

        int left = 0, target = 0;
        for (int i = 0; i < s.length(); i++) {
            Integer idx = idxmap.get(s.charAt(i));
            if( idx != null && idx.intValue() >= left ){
                if( i - left > target ){
                    target = i-left;
                }
                left = idx+1;
            }
            idxmap.put(s.charAt(i), i);
        }
        if( (s.length() - left) > target ){
            target = s.length() - left;
        }
        return target;
    }
}
